package org.xx.armory.swing.components;

import javax.swing.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;

/**
 * 用于显示图片的组件，该组件的尺寸和显示的图片的尺寸保持一致。
 */
public class ImageBox
        extends JComponent {
    private static final long serialVersionUID = 1L;

    private Image data;

    public ImageBox() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateUI() {
        setUI(UIManager.getUI(this));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getUIClassID() {
        return "ImageBoxUI";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void paintComponent(
            Graphics graphics
    ) {
        super.paintComponent(graphics);

        if (this.data == null) {
            return;
        }

        // 计算出绘制区域。
        final Insets insets = getInsets();
        final Rectangle r = new Rectangle(insets.left, insets.top, this.data.getWidth(null), this.data.getHeight(null));

        // 如果绘制区域和裁剪区域不相交则返回。
        if (!r.intersects(graphics.getClipBounds())) {
            return;
        }

        graphics.drawImage(this.data, insets.left, insets.top, null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension getPreferredSize() {
        int width;
        int height;

        if (this.data == null) {
            width = 0;
            height = 0;
        } else {
            width = this.data.getWidth(this);
            height = this.data.getHeight(this);
        }

        final Insets insets = this.getInsets();
        width += insets.left + insets.right;
        height += insets.top + insets.bottom;

        return new Dimension(width, height);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension getMaximumSize() {
        // 如果已设置最大尺寸，那么返回最大尺寸，否则使用最合适尺寸。
        if (isMaximumSizeSet()) {
            return super.getMaximumSize();
        }

        return this.getPreferredSize();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Dimension getMinimumSize() {
        // 如果已设置最小尺寸，那么返回最小尺寸，否则使用最合适尺寸。
        if (isMinimumSizeSet()) {
            return super.getMinimumSize();
        }

        return this.getPreferredSize();
    }

    public Image getData() {
        return this.data;
    }

    public void setData(
            Image data
    ) {
        Image oldValue = this.data;
        this.data = data;
        firePropertyChange("data", oldValue, data);

        if (data == null || !data.equals(oldValue)) {
            revalidate();
            repaint();
        }
    }
}
